import { defineStore } from 'pinia'
import { ref, computed, reactive } from 'vue'
import type { Goods } from '@/types/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    // state
    const cartList = ref<Goods[]>([])

    // 获取购物车列表
    // getters
    const getCartList = computed(() => cartList.value)

    // 获取选中的数量
    /**
    const getSelectTotal = computed(() => {
      let total = 0
      cartList.value.forEach(item => {
        if (item.state) {
          total += item.num
        }
      })

      return total
    })

    const getSelectAmount = computed<number>(() => {
      let amount = 0
      cartList.value.forEach(item => {
        if (item.state) {
          amount += item.num * item.price
        }
      })

      return amount
    })
     */
    /**
     * reducer中的参数
     *  参数1：函数（total，遍历的每一项 item）,然后把他们的值累加起来，注意：不要进行累加，就是直接加
     *  参数2：初始值
     */
    const getTotal = computed(() =>
      cartList.value.reduce((total, item) => total + item.num, 0)
    )

    const getSelectTotal = computed(() =>
      cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.num, 0)
    )

    const getSelectAmount = computed<number>(() =>
      cartList.value
        .filter(item => item.state)
        .reduce((total, item) => total + item.num * item.price, 0)
    )

    // 是否全部选中
    // const isAllSelect = computed(() => {
    //   let select = true
    //   cartList.value.forEach(item => {
    //     if (!item.state) {
    //       select = false
    //     }
    //   })

    //   return select
    // })
    const isAllSelect = computed(() => cartList.value.every(item => item.state))

    // actions
    // 加入购物车
    const addToCart = (goods: Goods) => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        // 之前有，则数量+你传递过来的数量
        oldGoods.num += goods.num
      } else {
        // 之前没有，则push到新数组中
        cartList.value.push(goods)
      }
    }

    // 更改仓库中的状态
    // goods 形参 ：右边是类型
    const updateGoodsState = (goods: { proid: string; state: boolean }) => {
      const oldGoods = cartList.value.find(item => item.proid === goods.proid)
      if (oldGoods) {
        oldGoods.state = goods.state
      }
    }

    // 更改仓库中数量
    // {proid,num} 形参（解构了的对象） ：右边是类型
    const updateGoodsNumber = ({
      proid,
      num
    }: {
      proid: string
      num: number
    }) => {
      const oldGoods = cartList.value.find(item => item.proid === proid)
      if (oldGoods) {
        oldGoods.num = num
      }
    }

    // 删除仓库中的商品
    const deleteGoodsById = (proid: string) => {
      // cartList.value = reactive(
      //   cartList.value.filter(item => item.proid != proid)
      // )
      const index = cartList.value.findIndex(item => item.proid === proid)
      if (index > -1) {
        cartList.value.splice(index, 1)
      }
    }

    const selectAllOrNot = (e: any) => {
      cartList.value.forEach(item => {
        item.state = e.detail
      })
    }

    return {
      cartList,
      getCartList,
      updateGoodsState,
      updateGoodsNumber,
      addToCart,
      deleteGoodsById,
      getSelectTotal,
      getSelectAmount,
      isAllSelect,
      selectAllOrNot,
      getTotal
    }
  },
  {
    // persist: true // web端没问题，默认存储在localStorage，但是小程序端不行
    persist: {
      key: 'cartList', // 存储在小程序 storage 中的key
      storage: {
        // key就是存储的key，值是就是你操作仓库之后的值
        setItem (key, value) {
          uni.setStorageSync(key, value)
        },
        getItem (key) {
          return uni.getStorageSync(key)
        }
      }
    }
  }
)
